import { mqttService } from '@/services/MQTTService';
import { userService } from '@/services/UserService';
import { topics } from '@/services/TopicConstants';

// 匹配相关主题
const CHESS_MATCHING_TOPIC = topics.CHESS_MATCHING;

// 匹配消息类型
export const ChessMatchingMessageType = {
  REQUEST: 'request',
  CANCEL: 'cancel',
  MATCHED: 'matched',
};

// 象棋匹配服务
export const chessMatchingService = {
  /**
   * 发送匹配请求
   */
  sendMatchingRequest() {
    if (!mqttService.isConnected.value) {
      console.error('MQTT未连接，无法发送匹配请求');
      return false;
    }

    const message = {
      type: ChessMatchingMessageType.REQUEST,
      userId: userService.userId.value,
      userName: userService.userName.value,
      timestamp: Date.now(),
    };

    mqttService.publish(CHESS_MATCHING_TOPIC, JSON.stringify(message));
    console.log('已发送象棋匹配请求:', message);
    return true;
  },

  /**
   * 取消匹配请求
   */
  cancelMatchingRequest() {
    if (!mqttService.isConnected.value) {
      console.error('MQTT未连接，无法取消匹配请求');
      return false;
    }

    const message = {
      type: ChessMatchingMessageType.CANCEL,
      userId: userService.userId.value,
      timestamp: Date.now(),
    };

    mqttService.publish(CHESS_MATCHING_TOPIC, JSON.stringify(message));
    console.log('已取消象棋匹配请求:', message);
    return true;
  },

  /**
   * 发送匹配成功消息
   * @param {Object} matchData 匹配数据
   */
  sendMatchedMessage(matchData) {
    if (!mqttService.isConnected.value) {
      console.error('MQTT未连接，无法发送匹配成功消息');
      return false;
    }

    const message = {
      type: ChessMatchingMessageType.MATCHED,
      roomId: matchData.roomId,
      players: matchData.players,
      timestamp: Date.now(),
    };

    mqttService.publish(CHESS_MATCHING_TOPIC, JSON.stringify(message));
    console.log('已发送象棋匹配成功消息:', message);
    return true;
  },

  /**
   * 订阅匹配主题
   */
  subscribeToMatchingTopic() {
    if (!mqttService.isConnected.value) {
      console.error('MQTT未连接，无法订阅匹配主题');
      return false;
    }

    mqttService.subscribe(CHESS_MATCHING_TOPIC);
    console.log('已订阅象棋匹配主题:', CHESS_MATCHING_TOPIC);
    return true;
  },

  /**
   * 取消订阅匹配主题
   */
  unsubscribeFromMatchingTopic() {
    if (!mqttService.isConnected.value) {
      console.error('MQTT未连接，无法取消订阅匹配主题');
      return false;
    }

    mqttService.unsubscribe(CHESS_MATCHING_TOPIC);
    console.log('已取消订阅象棋匹配主题:', CHESS_MATCHING_TOPIC);
    return true;
  },
}; 